<template>
	<!-- 建设验收审核 -->
	<div>
		<!-- 搜索 -->
		<TopFilter
			ref="commonTopFilter"
			:list="topFilterInit"
			:cols="3"
			labelWidth="100"
			@filterChange="changeHandle"
			@onCollapse="collapseHandle"
		/>
		<!-- 经销商弹窗 -->
		<BaseDialog
			title="经销商查询"
			:visible.sync="visibleDealer"
			width="1000px"
			destroyOnClose
			:containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
		>
			<!-- <dealer-madal ref="addDialog" @close="closeDealer" /> -->
			<dealer-madal  ref='addDialog' selectType='multiple' v-model="initDealerData"  @close="closeDealer" />
		</BaseDialog>
	</div>
</template>

<script>
	import dealerMadal from '@/pages/cms-common/dealerdata'
	import { dictionary } from '@/utils/dictMixin';
	import { region } from '@/api/cms-common/region';//行政区域
	import { getRegion, getCommunity,getLevelOneArea, getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index';//事业部，办事处
	import { dealerCommon, DICT_CODE } from '@/api/cms-api/origin/commonDealerType';		//经销商类型工具类
  import {getModelAll} from '@/api/cms-common/basedata';
	export default {
		mixins: [dictionary,region,dealerCommon],
		components: {
			dealerMadal
		},
		props:{
			defaultStatus: {
				type: [String,Array],
				required: false,
				default:()=>{
					return '';
				}
			}
		},
		data() {
			return {
				visibleDealer: false,
				initDealerData:{},  //经销商弹窗参数
				dealerIds:[],
				topFilterInit: this.topFilterInitFun(),
        ORG_TYPE_MARKETING_WAR_AREA:15061013, //C端战区 营销战区
        ORG_TYPE_MARKETING_BIG_AREA:15061014, //C端大区 营销大区
        ORG_TYPE_MARKETING_SMALL_AREA:15061015, //C端小区 营销小区
        ORG_TYPE_OUTING_WAR_AREA:15061016, //B端战区
        ORG_TYPE_OUTING_BIG_AREA:15061017, //B端大区
        ORG_TYPE_OUTING_SMALL_AREA:15061018, //B端小区
        ORG_TYPE_SERVICE_BIG_AREA:15061019, //服务大区
        ORG_TYPE_SERVICE_SMALL_AREA:15061020, //服务小区
			};
		},
		mounted(){
			this.initProvince();
      this.getTopLevelArea(this.ORG_TYPE_MARKETING_WAR_AREA,'marketingWarArea');
      this.getTopLevelArea(this.ORG_TYPE_OUTING_WAR_AREA,'outingWarArea');
		},
		methods: {
			transformStatus(val){
				if(!Array.isArray(val)){
					let status = parseInt(val);
					if(isNaN(status)){
						return null;
					}else{
						return status;
					}
				}else{
					return val;
				}
			},
			//初始化所在省份
			async initProvince(){
				let pl = await this.createRegionList();
				this.topFilterInit.find(item => item.fieldName === 'provinceId').itemList = pl;
			},
			//初始化所在市数据
			async initCity(provinceId){
				if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
					return;
				}
				//取省数据
				let rd = this.getRegionData();
				this.cityData = rd[provinceId].children;
				let cl = this.createSubRegionList(this.cityData);
				//初始化市，清除原值
				let city = this.topFilterInit.find(item => item.fieldName === 'cityId');
				city.itemList = cl;
				city.initialValue = '';
				//清除区县
				let district = this.topFilterInit.find(item => item.fieldName === 'districtId');
				district.itemList = [];
				district.initialValue = '';
			},
			//初始化所在县市数据
			async initTown(cityId){
				if(!cityId || cityId==null || typeof(cityId)=='undefined'){
					return;
				}
				let td = this.cityData[cityId].children;
				let tl = this.createSubRegionList(td);
				//初始化区县，清除原值
				let district = this.topFilterInit.find(item => item.fieldName === 'districtId');
				district.itemList = tl;
				district.initialValue = '';
			},
			//搜索获取数据
			changeHandle(val) {

        this.multiSelectJoin(val,['dealerType','dealerStatus','constructType','constructLevel','modelName']);

				this.$emit('filterChange', val)
			},
			collapseHandle() {
				this.$emit('onCollapse', this.selectRow)
			},
			// 经销商打开窗口 -传数据
			dealerHandle() {
				this.initDealerData={
					excludeBigCustomer:false,//是否查询大客户经销商，如果查询 true，不查询 false
				}
				this.visibleDealer = true;
			},
			// 经销商关闭窗口 -返回数据
			closeDealer(data) {
				let dealerCodes = [];
				let dealerNames = [];
				if(data && data.data && data.data.length > 0){
					for(let i in data.data){
						dealerCodes.push(data.data[i].dealerCode);
						dealerNames.push(data.data[i].dealerName);
					}
				}

				this.topFilterInit.find(item => item.fieldName === 'dealerNames').initialValue = dealerNames.join(",");
				this.dealerCodes = dealerCodes;
				this.visibleDealer = data.visible; //关闭弹窗
			},
			//搜索数据
			topFilterInitFun() {
				return [
          { type: 'INPUT', label: '公司代码', fieldName: 'dealerCompanyCode', initialValue: ''},
					{ type: 'INPUT', label: '经销店代码', fieldName: 'dealerCode', initialValue: ''},
          { type: 'INPUT', label: '经销商名称',fieldName : 'dealerName', placeholder: '请输入', initialValue: ''},
					{ type: 'INPUT', label: '经销商简称',fieldName : 'dealerShortname', placeholder: '请输入', initialValue: ''},
          { type: 'SELECT', label: '营销战区',fieldName : 'marketingWarArea', placeholder: '请输入', initialValue: ''
            ,itemList: [],
            change: val => {
              this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_MARKETING_BIG_AREA,
                'marketingWarArea','marketingBigArea','marketingSmallArea');
            },
          },
          { type: 'SELECT', label: '所属大区',fieldName : 'marketingBigArea', placeholder: '请输入', initialValue: ''
            ,itemList: [],
            change: val => {
              this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_MARKETING_SMALL_AREA,
                'marketingBigArea','marketingSmallArea','marketingSmallArea');
          },
            },
          { type: 'SELECT', label: '所属区域',fieldName : 'marketingSmallArea', placeholder: '请输入', initialValue: ''
            ,itemList: [],
            // change: val => {
            //   this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_MARKETING_SMALL_AREA,
            //     'marketingSmallArea','marketingSmallArea','marketingSmallArea');
            // },
          },
          { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [],change: props => this.initCity(props)},
          { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [], change: props => this.initTown(props)},
          { type: 'SELECT', label: '县区', fieldName: 'districtId', placeholder: '请选择', initialValue: '', itemList: [] },
          { type: 'MULTIPLE_SELECT', label: '建店类型', fieldName: 'constructType', placeholder: '请选择', initialValue: '', itemList: this.createDictList('1727') },
          { type: 'MULTIPLE_SELECT', label: '建店级别', fieldName: 'constructLevel', placeholder: '请选择', initialValue: '', itemList: this.createDictList('1720') },
          { type: 'MULTIPLE_SELECT', label: '经营状态', fieldName: 'dealerStatus', placeholder: '请选择', initialValue: '', itemList: this.createDictList('1724') },
          { type: 'MULTIPLE_SELECT', label: '授权车型', fieldName: 'modelName', placeholder: '请选择', initialValue: '', itemList: this.getModel() }
          // { type: 'MULTIPLE_SELECT', label: '经销商类型',fieldName : 'dealerType', placeholder: '请输入', initialValue: '', itemList: this.createDictList('1721')},
				];
			},
      //获取所有车型
      async getModel() {
        let res = await getModelAll();
        if (res.resultCode === 200) {
            this.topFilterInit.find(item => item.fieldName === 'modelName').itemList = res.data.map(x => ({text:x.modelName,value:x.modelId}));

        }
      },
      //多项选择格式化
      multiSelectJoin(obj, keys) {
        keys.forEach(key => {
          const data = obj[key];
          if (Array.isArray(data)) {
            obj[`${key}Str`] = data.join(",");
          }else {
            obj[`${key}Str`] = null;
          }
        });
      },

      //获取顶层组织数据
      async getTopLevelArea(areaType, filedName) {
        const res = await getLevelOneArea(areaType);
        if (res.resultCode === 200) {
          this.topFilterInit.find(item => item.fieldName === filedName).itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
        }
      },

      //顶层和中层组织数据修改
      async changeTopAndMiddleLevelArea(deptId, sonAreaType, parentFieldName, sonFieldName,smallFieldName, flag = true) {
        let parentArea = this.topFilterInit.find(item => item.fieldName === parentFieldName);
        let sonArea = this.topFilterInit.find(item => item.fieldName === sonFieldName);
        let smallArea = this.topFilterInit.find(item => item.fieldName === smallFieldName);
        if (!deptId) {
          sonArea.initialValue = '';
          sonArea.itemList = [];
          smallArea.initialValue = '';
          smallArea.itemList = [];
        } else {
          if (flag) {
            //正常的级联，清空原来选择的数据
            sonArea.initialValue = '';
            smallArea.initialValue = '';
          }
          const res = await getLevelTwoAndThreeArea(sonAreaType, deptId);
          if (res.resultCode === 200) {
            sonArea.itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
          }
        }
      },

		},
	};
</script>

<style lang="less" scoped>
</style>
